package ui.activity;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.fy.fyzf.R;
import com.fy.fyzf.base.BaseActivity;
import com.fy.fyzf.bean.BaseData;
import com.fy.fyzf.bean.HousesListBean;
import com.fy.fyzf.bean.RecordBean;
import com.fy.fyzf.bean.UserInfoBean;
import com.fy.fyzf.dialog.LoopViewPopwindow;
import com.fy.fyzf.glideUtils.GlideUtils;
import com.fy.fyzf.oss.MyOSSUtils;
import com.fy.fyzf.presenter.SelfPresenter;
import com.fy.fyzf.utils.AppUtils;
import com.fy.fyzf.utils.PhoneFormatCheckUtils;
import com.fy.fyzf.utils.SPUtils;
import com.fy.fyzf.view.SelfInfoCallBack;
import com.fy.fyzf.weight.GlideEngine;
import com.lljjcoder.citypickerview.widget.CityPicker;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.PictureSelectionConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureParameterStyle;
import com.luck.picture.lib.tools.SdkVersionUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class SelfInfoActivity extends BaseActivity<SelfPresenter> implements SelfInfoCallBack,MyOSSUtils.OssUpCallback {

    @BindView(R.id.iv_logo)
    ImageView ivLogo;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.et_tel)
    EditText etTel;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_card_number)
    EditText tvCardNumber;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.rl_address)
    RelativeLayout rlAddress;
    @BindView(R.id.et_census)
    TextView etCensus;
    @BindView(R.id.rl_census)
    RelativeLayout rlCensus;
    private String imgPath;

    @Override
    protected SelfPresenter createPresenter() {
        return new SelfPresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_self_info;
    }

    @Override
    public void getSelfInfoSuccess(UserInfoBean userInfoBean) {
        GlideUtils.loadBordoerImg(userInfoBean.getUserPortrait(), ivLogo,this);
        if (userInfoBean.getUserSex() == 1) {
            tvSex.setText("男");
        } else {
            tvSex.setText("女");
        }
        etTel.setText(userInfoBean.getUserMobile());
        tvTime.setText(userInfoBean.getUserEntryTime());
        tvCardNumber.setText(userInfoBean.getUserCard());
        tvAddress.setText(userInfoBean.getUserAddress());
        etCensus.setText(userInfoBean.getUserHousehold());
    }

    private String logo;
    @Override
    public void upLoadImgSuccess(BaseData baseData) {

    }

    @Override
    public void updataSlefInfoSuccess(BaseData baseData) {
        AppUtils.showToast("修改成功");
        SPUtils.getInstance(this).putString("logo", logo);
        EventBus.getDefault().post("exchangeSuccess");
        finish();
    }

    @Override
    public void getMsgCountSuccess(BaseData baseData) {

    }

    @Override
    public void changePwdSuccess(BaseData baseData) {

    }

    @Override
    public void getChangeMsgSuccess(List<RecordBean> list) {

    }

    @Override
    public void getMyHousingSuccess(HousesListBean housesListBean) {

    }

    @Override
    public void initView() {
        super.initView();
        setTitleName("个人资料");
    }

    @Override
    public void initData() {
        super.initData();
        mPresenter.getSelfInfo();
    }

    private List<String> sexList ;
    private List<Integer> list ;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @OnClick({R.id.rl_address, R.id.rl_census,R.id.iv_logo, R.id.tv_sex, R.id.tv_time, R.id.tv_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_logo:
                showPic();
                break;
            case R.id.tv_sex:
                sexList = new ArrayList<>();
                list = new ArrayList<>();
                sexList.add("男");
                sexList.add("女");

                list.add(1);
                list.add(0);
                showSexSelect(sexList, list);
                break;
            case R.id.tv_time:
                showDateDialog();
                break;
            case R.id.tv_save:
                if (TextUtils.isEmpty(tvSex.getText().toString()) ||TextUtils.isEmpty(etTel.getText().toString()) || TextUtils.isEmpty(tvTime.getText().toString())
                                ||TextUtils.isEmpty(tvCardNumber.getText().toString()) ||TextUtils.isEmpty(tvAddress.getText().toString())  ||TextUtils.isEmpty(etCensus.getText().toString())  ) {
                    AppUtils.showToast("输入信息不完整");
                    return;
                }

                if (!PhoneFormatCheckUtils.isIDNumber(tvCardNumber.getText().toString())) {
                    AppUtils.showToast("身份证号不正确");
                    return;
                }
                mPresenter.updataSelfInfo(logo,sexId,etTel.getText().toString(),tvTime.getText().toString(),tvCardNumber.getText().toString(),tvAddress.getText().toString(),etCensus.getText().toString());
                break;
            case R.id.rl_address:
                showCitySelect(1);
                break;
            case R.id.rl_census:
                showCitySelect(2);
                break;
        }
    }

    private void showCitySelect(int type){
        CityPicker cityPicker = new CityPicker.Builder(this)
                .textSize(13)
                .title("")
                .titleBackgroundColor("#FFFFFF")
                .confirTextColor("#39C3F2")
                .cancelTextColor("#39C3F2")
                .province("浙江省")
                .city("杭州市")
                .district("江干区")
                .textColor(Color.parseColor("#000000"))
                .provinceCyclic(true)
                .cityCyclic(false)
                .districtCyclic(false)
                .visibleItemsCount(7)
                .itemPadding(15)
                .onlyShowProvinceAndCity(false)
                .build();
        cityPicker.show();
        cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
            @Override
            public void onSelected(String... citySelected) {
                //省份
                String province = citySelected[0];
                //城市
                String city = citySelected[1];
                //区县（如果设定了两级联动，那么该项返回空）
                String district = citySelected[2];
                //为TextView赋值
                if (type == 1) {
                    tvAddress.setText(province.trim() + "-" + city.trim() + "-" + district.trim());
                } else {
                    etCensus.setText(province.trim() + "-" + city.trim() + "-" + district.trim());
                }
            }
        });
    }
    private int sexId;
    private String joinTime;

    private void showSexSelect(List<String> titles, List<Integer> idS) {
        LoopViewPopwindow loopViewPopwindow = new LoopViewPopwindow(this);
        loopViewPopwindow.setIds(idS).setTitleData(titles).setTitle("name").showPop(tvSex);
        loopViewPopwindow.getView(R.id.tv_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loopViewPopwindow.dismiss();
                sexId = idS.get(loopViewPopwindow.position);
                tvSex.setText(titles.get(loopViewPopwindow.position));
            }
        });
    }

    private void showPic() {
        PictureSelector.create(SelfInfoActivity.this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
//                        .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style v2.3.3后 建议使用setPictureStyle()动态方式
                .isWeChatStyle(true)// 是否开启微信图片选择风格
                .isUseCustomCamera(false)// 是否使用自定义相机
                .setLanguage(-1)// 设置语言，默认中文
                .setPictureStyle(new PictureParameterStyle())// 动态自定义相册主题
                .setPictureWindowAnimationStyle(null)// 自定义相册启动退出动画
                .isWithVideoImage(true)// 图片和视频是否可以同选,只在ofAll模式下有效
                .isMaxSelectEnabledMask(true)// 选择数到了最大阀值列表是否启用蒙层效果
                .maxSelectNum(16)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .maxVideoSelectNum(1) // 视频最大选择数量
                .imageSpanCount(3)// 每行显示个数
                .isReturnEmpty(false)// 未选择数据时点击按钮是否可以返回
                .closeAndroidQChangeWH(true)//如果图片有旋转角度则对换宽高,默认为true
                .closeAndroidQChangeVideoWH(!SdkVersionUtils.checkedAndroid_Q())// 如果视频有旋转角度则对换宽高,默认为false
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                .isOriginalImageControl(false)// 是否显示原图控制按钮，如果设置为true则用户可以自由选择是否使用原图，压缩、裁剪功能将会失效
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .isSingleDirectReturn(true)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                .isPreviewImage(true)// 是否可预览图片
                .isPreviewVideo(false)
                //.querySpecifiedFormatSuffix(PictureMimeType.ofJPEG())// 查询指定后缀格式资源
                .isEnablePreviewAudio(false) // 是否可播放音频
                .isCamera(true)// 是否显示拍照按钮
                //.isMultipleSkipCrop(false)// 多图裁剪时是否支持跳过，默认支持
                //.isMultipleRecyclerAnimation(false)// 多图裁剪底部列表显示动画效果
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg,Android Q使用PictureMimeType.PNG_Q
                .isEnableCrop(false)// 是否裁剪
                .isCompress(true)// 是否压缩
                .synOrAsy(false)//同步true或异步false 压缩 默认同步
                .compressSavePath(Environment.getExternalStorageState())//压缩图片保存地址
                .isGif(false)// 是否显示gif图片
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .circleDimmedLayer(true)// 是否圆形裁剪
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .isOpenClickSound(false)// 是否开启点击声音
                .cutOutQuality(90)// 裁剪输出质量 默认100
                .minimumCompressSize(100)// 小于多少kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void showDateDialog() {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                int  str;
                if (month == 0) {
                    str = 1;
                } else {
                    str = month + 1;
                }
                tvTime.setText(year + "-" + str + "-" + dayOfMonth);
                joinTime = year + "-" + str + "-" + dayOfMonth + " 00:00:00";
            }
        },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONDAY),
                calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));

        DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                // TODO Auto-generated method stub
                System.out.println(year + "-" + monthOfYear + "-" + dayOfMonth);
            }
        };
        dialog.show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
           /* if (android.os.Build.VERSION.SDK_INT == 29) {
                imgPath = selectList.get(0).getAndroidQToPath();
            } else {

            }*/
            imgPath = AppUtils.getPath(SelfInfoActivity.this, Uri.parse(selectList.get(0).getPath()));
            File file = new File(imgPath);
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
//            mPresenter.upLoadImg(body);
            MyOSSUtils.getInstance().upImage(SelfInfoActivity.this,SelfInfoActivity.this, System.currentTimeMillis() + ".jpg", imgPath);
        }
    }

    @Override
    public void successImg(String img_url) {
        Log.e("OssImg", img_url);
        logo = img_url;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                GlideUtils.loadBordoerImg(img_url, ivLogo,SelfInfoActivity.this);
            }
        });
    }

    @Override
    public void successVideo(String video_url) {

    }

    @Override
    public void inProgress(long progress, long zong) {

    }
}